package com.captcha;

import com.captcha.generator.AbstractCaptcha;
import com.captcha.utils.RandomUtils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImagingOpException;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Author: 随风飘的云
 * @Description: Png图片格式生成器
 * @Date: 2022/3/7 13:11
 * @Modified By:
 */
public class PngCaptcha extends AbstractCaptcha{

    public BufferedImage RenderImage(String text) {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        // 获取图片宽高
        int width = getConfig().getWidth();
        int height = getConfig().getHeight();

        // 创建图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取画笔
        Graphics2D graphics = image.createGraphics();

        // 设置抗拒齿
        graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        // 填充背景
        FillBackGround(graphics, width, height);

        // 设置字体厚度
        int textThickness = getConfig().getTextThickness();
        graphics.setStroke(new BasicStroke((float) textThickness, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL));

        // 验证码内容转数组
        char[] strs = text.toCharArray();

        // 每一个字符所占的宽度
        int fontWidth = width / strs.length;

        // 获取字体的规格
        FontMetrics fontMetrics = graphics.getFontMetrics();

        // 字符的左右边距
        int fontSpace = (fontWidth - (int) fontMetrics.getStringBounds("W", graphics).getWidth()) / 2;

        int len = strs.length;
        for (int i = 0; i < len; i++) {
            // 为每一个字设置独立的颜色
            graphics.setColor(getTextColor());
            // 设置字体
            setImageFont(graphics);
            // 文字的纵坐标
            int fontY = height - ((height - (int) fontMetrics.getStringBounds(String.valueOf(strs[i]), graphics).getHeight()) >> 1);
            // 画内容到图片上
            graphics.drawString(String.valueOf(strs[i]), i * fontWidth + fontSpace - 10, fontY + 5);
        }

        if(getConfig().addShear()){

            // 扭曲验证码图片
            Shear(graphics, width, height, getConfig().getBackgroundColor());
        }

        // 填充边框
        if(getConfig().isBorder()){
            setImageBoard(graphics);
        }

        // 画干扰圆
        drawCircle(getConfig().getNoiseNumber(), graphics);

        // 画干扰线
        drawBasselLine(getConfig().getShadeNumber(), graphics);

        // 提起画笔，释放资源
        graphics.dispose();

        this.imageBytes = out.toByteArray();

        try {
            out.close();
        } catch (IOException e) {
            throw new ImagingOpException("Image output stream close failed");
        }

        return image ;
    }
}
